/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.message.service.note.impl;

import com.je.common.base.util.MessageUtils;
import com.je.message.exception.MessageSendException;
import com.je.message.rpc.NoteRpcService;
import com.je.message.service.note.NoteTypeEnum;
import com.je.meta.rpc.setting.MetaSystemSettingRpcService;
import com.je.meta.util.SettingHelper;
import com.je.meta.util.setting.push.NoteWj;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import com.je.message.service.note.AbstractNoteServiceImpl;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.HttpClientUtils;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;

/**
 * @program: jecloud-message
 * @author: LIULJ
 * @create: 2021/8/18
 * @description: 中国网建短信发送实现
 */
@Service("noteWebChineseService")
public class NoteWebChineseServiceImpl extends AbstractNoteServiceImpl implements NoteRpcService {

    @Autowired
    private MetaSystemSettingRpcService metaSystemSettingRpcService;
    final String SENDNOTE_URL = "http://utf8.api.smschinese.cn/";

    @Override
    public int sendNote(String phoneNumber, String context)  {
        String noteType = metaSystemSettingRpcService.requireSettingValue("JE_SYS_NOTEDIY");
        if (!NoteTypeEnum.NOTESYS.getName().equals(noteType)) {
            throw new MessageSendException(MessageUtils.getMessage("message.interface.type.mismatch"));
        }
        NoteWj noteWjConfig = SettingHelper.getNoteWjConfig();
        String uid = noteWjConfig.getUid();
        String key = noteWjConfig.getKey();
        String url = String.format("%s?Uid=%s&Key=%s&smsMob=%s&smsText=%s", SENDNOTE_URL, uid, key, phoneNumber, context);
        //生成httpclient，相当于该打开一个浏览器
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        //创建get请求，相当于在浏览器地址栏输入 网址
        HttpGet request = new HttpGet(url);
        //伪装头
        request.setHeader("User-Agent", "Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.159 Mobile Safari/537.36");
        int result = 0;
        try {
            //执行get请求，相当于在输入地址栏后敲回车键
            response = httpClient.execute(request);

            //判断响应状态为200，进行处理
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                //5.获取响应内容
                HttpEntity httpEntity = response.getEntity();
                result = Integer.parseInt(EntityUtils.toString(httpEntity, "utf-8"));
            } else {
                new Exception(EntityUtils.toString(response.getEntity(), "utf-8"));
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //关闭资源
            HttpClientUtils.closeQuietly(response);
            HttpClientUtils.closeQuietly(httpClient);
        }
        if (result < 0) {
            throw  new MessageSendException(MessageUtils.getMessage("message.message.failed.to.send"));
        }
        return 1;
    }

}
